<template>
    <div id="cont">
			<div class="count">
				<input type="text" v-model="name" placeholder="标签名..."><a href="javascript:" @click="add">添加</a>
			</div>
			<div class="clearfloat">
				<div class="col-2 label" v-for="(it, k) in labels" :key="k">
					<h3>{{it.name}}</h3>
					<p style="text-align: center;"></p>
					<p style="text-align: right;"><a href="javascript:;" @click="del(it._id, k)" class="btn">删除</a></p>
				</div>
			</div>
    </div>
</template>

<script>
import axios from 'axios';
import app from '@/utils';
import { mapActions } from 'vuex';

export default {
	name: 'Label',
	data() {
		return {
			name: '',
			labels: [],
		}
	},
	mounted() {
		this.getLabel();
	},
	methods: {
		...mapActions([
			'SET_LABELS',
			'DEL_LABELS'
		]),
		add() {
			app.request({
				url: '/api/label/edit',
				method: 'POST',
				data: {
					name: this.name,
				},
				success: response => {
					let res = response.data;
					if(res.s) {
						app.flash('success', '添加成功~');
						this.labels.push(res.d);
					}else {
						app.flash('error', res.m);
					}
				}
			})
		},
		getLabel() {
			const labels = this.$store.state.labels;
			if(labels && labels.length > 0) {
				this.labels = labels;
			}else {
				app.request({
					url: '/api/label/list',
					success: (response) => {
						let res = response.data;
						if(res.s) {
							this.labels = res.d;
							this.SET_LABELS(res.d);
						}
					}
				})
			}
		},
		del(id, i) {
			app.request({
				url: '/api/label/del',
				method: 'DELETE',
				data: {
					id
				},
				success: response => {
					const res = response.data;
					if(res.s) {
						app.flash('success', '删除成功~');
						this.labels.splice(i, 1);
						this.$store.dispatch('DEL_LABELS', i);
					}else {
						app.flash('error', res.m);
					}
				}
			})
		}
	}
}
</script>

<style scoped>
	.count {margin-bottom: 50px; text-align: center;}
	.count input {width: 30%; height: 38px; padding: 0 10px; border-radius: 3px; border: 0; box-shadow: 0 0 5px #ddd; outline: 0;}
	.count a {display: inline-block; margin-left: 15px; width: 80px; height: 38px; line-height: 38px; border-radius: 4px; color: #fff; background-color: #4eba0f;}
	.label {margin: 10px; padding: 10px; border-radius: 3px; box-shadow: 0 0 5px #ddd; background-color: #fff; cursor: pointer;}
	.label h3 {margin: 0;}
	.label p {margin: 0;}
	.label a {font-size: 12px; color: #808080; transition: all .5s;}
	.label a:hover {color: #666;}
</style>
